package com.youxin.logprocess.controller;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.log4j.Logger;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import com.youxin.busfoundation.config.MonitorBaseBean;
import com.youxin.busfoundation.config.MonitorMysqlConfig;
import com.youxin.foundation.lang.BaseException;
import com.youxin.foundation.utils.thread.ScheduleThreadPool;
import com.youxin.logprocess.common.MonitorGlobalConfig;
import com.youxin.logprocess.mysql.DbHelper;

/**
 * MySql控制器
 * 
 * @author yingde.cao
 *
 */
public class MonitorMySqlController extends BaseMonitorController{
	private static Logger logger = Logger.getLogger(MonitorMySqlController.class);
	private MonitorMysqlConfig config;

	private static MonitorMySqlController controller = new MonitorMySqlController();

	public static void initConfig(MonitorMysqlConfig config) {
		controller.setConfig(config);
	}
	
	public MonitorMysqlConfig getConfig() {
		return config;
	}

	public void setConfig(MonitorMysqlConfig config) {
		this.config = config;
	}
	
	public static MonitorMySqlController instance(){
		return controller;
	}

	@Override
	public MonitorBaseBean getMonitorBean() {
		return config;
	}
	/**
	 * 执行方法
	 */
	public void execute() {
		if(config==null)
		{
			throw new BaseException("请配置mointor.mysql的config");
		}
		if (config.getMonitor() != 1) {
			return;
		}
		
		for (DriverManagerDataSource dataConfig : config.getDatasources()) {
			ScheduleThreadPool.scheduleWithFixedDelay(new Runnable() {
				@Override
				public void run() {
					try {
						querySlaveStatus(dataConfig);
					} catch (Exception e) {
						logger.error("执行任务异常:",e);
						add(dataConfig.getUrl(),"配置信息1:\n"+dataConfig.getUrl()+"\n"+e);
					}
				}
			}, config.getInterval(), MonitorGlobalConfig.START_DELAY_TIME);
		}
	}

	private void querySlaveStatus(DriverManagerDataSource dataConfig) {
		String sql = "select 1";
		DbHelper db =null;
		try {
			db = new DbHelper(dataConfig.getUrl(), dataConfig.getUsername(), dataConfig.getPassword());
			db.execute((dbStateMent -> {
				ResultSet ret = null;
				try {
					ret = dbStateMent.executeQuery(sql);		
					while (ret.next()) {
						/**
						 * Object valor = ret.getObject(1);
						 */
					}
				} catch (Exception e) {
					logger.error("执行show slave status异常:",e);
					add(dataConfig.getUrl(),"配置信息2:\n"+dataConfig.getUrl()+"\n"+ e);
				}
				finally {
					try {
						if(ret!=null){
							ret.close();
						}
					} catch (Exception e) {
						logger.error("执行ret.close异常:",e);
					}
				}
			}));
			
		} catch (Exception e) {
			add(dataConfig.getUrl(), e);
		}finally {
			try {
				if(db!=null){
					db.close();
				}
			} catch (Exception e) {
			}
		}
		

	}

}
